package com.jenkins.test.cron;

import com.jenkins.test.cron.task.JobRunnable;
import com.jenkins.test.cron.task.TaskRunnableContent;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.ScheduledFuture;

/**
 * @version V1.0.0
 * @ClassName: {@link ScheduleServiceImpl}
 * @Description: 定时器任务抽象
 * @author: Lanzhou
 * @date: 2021/6/28 15:14
 * @Copyright:2020 All rights reserved.
 */
@Service
public class ScheduleServiceImpl implements ScheduleService {

    @Resource
    private ScheduleJobContext context;

    @Resource
    private ThreadPoolTaskScheduler threadPoolTaskScheduler;

    /**
     * 停止任务
     *
     * @param key yz
     */
    @Override
    public void stopJob(String key) {
        if (null != context.getJobContext(key)) {
            context.getJobContext(key).cancel(true);
        }
    }

    /**
     * 删除任务
     *
     * @param key yz
     */
    @Override
    public void deleteJob(String key) {
        if (null != context.getJobContext(key)) {
            context.getJobContext(key).cancel(true);
            context.delJobContext(key);
        }
    }

    /**
     * 重启
     *
     * @param bean
     */
    @Override
    public void restartJob(ScheduleBean bean) {
        this.stopJob(bean.getKey());
        this.registerJob(bean);
    }

    /**
     * 注册任务
     *
     * @param bean 实体
     */
    @Override
    public void registerJob(ScheduleBean bean) {
        String key = bean.getKey();
        String cron = bean.getCron();
        // 原来有的话不注册了, 直接溜了
        if (null != context.getJobContext(key)) {
            return;
        }
        JobRunnable jobTask = TaskRunnableContent.getJobTask(key);
        if (null == jobTask) {
            throw new RuntimeException("不支持的任务信息");
        }
        ScheduledFuture<?> schedule = threadPoolTaskScheduler.schedule(jobTask, new CronTrigger(cron));
        context.setJobContext(key, schedule);
    }

    /**
     * 刷新任务
     *
     * @param bean 实体
     */
    @Override
    public void flushJob(ScheduleBean bean) {
        String key = bean.getKey();
        // 将原定时任务移除, 然后重启一下(更新配置)
        if (null != context.getJobContext(key)) {
            context.getJobContext(key).cancel(true);
        }
        this.registerJob(bean);
    }

}
